<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>观察者模式</title>
</head>
<body>
    <script>
        // 发布者-目标
        class Dep{
            constructor() { 
                //记录所有的观察者
                this.subs = [];
            }
            // 添加订阅者
            addSub(sub) {
                if (sub && sub.update){
                    this.subs.push(sub)
                }
            }
            // 发布通知
            notify() {
                this.subs.forEach(sub => {
                    sub.update()
                });
            }
        }
        // 订阅者
        class Watcher{
            update(){
                console.log('update')
            }
        }


        let dep = new Dep()
        let watcher = new Watcher()
        dep.addSub(watcher)
        dep.notify()
    </script>
</body>
</html>